package com.mars.weixin.jobs;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.mars.component.scheduler.model.SchedulerJob;
import com.mars.component.scheduler.service.SchedulerService;
import com.mars.weixin.api.JsTicket;
import com.mars.weixin.api.JsTicketApi;
import com.mars.weixin.api.JsTicketApi.JsApiType;
import com.mars.weixin.common.WeixinContext;

/**
 * 定时获取微信JsApiTicket 票据每2小时获取一次
 * 
 * @author yhaoquan
 * 
 */
public class JsApiTicketRefreshJob implements Job {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private SchedulerService schedulerService ;

	/**
	 * Spring容器启动执行
	 */
	public void initRunScheduler() {
		JsTicket jsTicket = JsTicketApi.getJsTicket(JsApiType.jsapi) ;
		WeixinContext.setJsApiTicket(jsTicket.getTicket());
		logger.info("保存JsApi-Ticket票据到微信上下文:{}", jsTicket.getTicket());
		
		//创建定时任务
		SchedulerJob job = new SchedulerJob() ;
		job.setJobId("JsApi-Ticket");
		job.setJobName("微信JsApiTicket票据");
		job.setJobGroup("weixin");
		job.setClassName("com.mars.weixin.jobs.JsApiTicketRefreshJob");
		job.setCronExpression("0 55 0/1 * * ?");
		job.setDescription("微信JSAPI-Ticket票据获取，每隔1小时55分刷新一次AccessToken");
		
		this.schedulerService.createScheduleJob(JsApiTicketRefreshJob.class, job);
	}
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JsTicket jsTicket = JsTicketApi.getJsTicket(JsApiType.jsapi) ;
		WeixinContext.setJsApiTicket(jsTicket.getTicket());
	}
	
}
